package cn.edu.xjtu.daily.April.day_4_13;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @author Hydrion-QLz
 * @date 2022-04-13 12:13
 * @description P4913 【深基16.例3】二叉树深度:https://www.luogu.com.cn/problem/P4913
 */
public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StreamTokenizer in = new StreamTokenizer(br);

    static int nextInt() throws IOException {
        in.nextToken();
        return (int) in.nval;
    }

    public static void main(String[] args) throws IOException {
        int n = nextInt();
        Map<Integer, TreeNode> map = new HashMap<>();
        TreeNode root = new TreeNode(1);
        map.put(root.val, root);

        // 读入输入样例
        for (int i = 1; i <= n; i++) {
            int l = nextInt();
            int r = nextInt();
            TreeNode node = map.get(i);
            if (l != 0) {
                TreeNode leftNode = new TreeNode(l);
                node.left = leftNode;
                map.put(l, leftNode);
            }
            if (r != 0) {
                TreeNode rightNode = new TreeNode(r);
                node.right = rightNode;
                map.put(r, rightNode);
            }
        }
        // int depth = getDepth(root); // dfs遍历

        // bfs 遍历，用例2RE，不知道为啥
        Deque<TreeNode> queue = new LinkedList<>();
        queue.addFirst(root);
        int depth = 0;
        while (!queue.isEmpty()) {
            depth++;
            int size = queue.size();
            while (size != 0) {
                size--;
                TreeNode node = queue.removeLast();
                if (node.left != null) queue.addFirst(node.left);
                if (node.right != null) queue.addFirst(node.right);
            }
        }
        System.out.println(depth);
    }

    /**
     * dfs搜索，用例1,2,5,RE，应该是超过系统递归栈容量了
     *
     * @param root
     * @return
     */
    private static int getDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftDepth = getDepth(root.left);
        int rightDepth = getDepth(root.right);
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }
}
